package com.lishe.lishe.lishe.module.mall.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerviewBaseAdapter;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.SpaceItemDecoration;
import com.lishe.lishe.lishe.module.commonclass.SearchActivity;
import com.lishe.lishe.lishe.module.mall.activity.GoodsDetailActivity;
import com.lishe.lishe.lishe.module.mall.adapter.ClassificationMallAdapter;
import com.lishe.lishe.lishe.module.mall.bean.category.CategoryGoods;
import com.lishe.lishe.lishe.module.mall.presenter.ClassificationPresenter;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.bean.DataPageItemBody;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;

/**
 * Created by yang on 2017/11/6.
 * 分类商城
 */

public class ClassificationMallActivity extends BaseActivity implements View.OnClickListener {
    private static final int SEARCH_REQUEST = 1001;

    public static void jump(Activity activity, String cate_id, String original_cate_id, boolean loadMore, String title) {
        Intent intent = new Intent(activity, ClassificationMallActivity.class);
        intent.putExtra("cate_id", cate_id);
        intent.putExtra("original_cate_id", original_cate_id);
        intent.putExtra("loadMore", loadMore);
        intent.putExtra("title", title);
        activity.startActivity(intent);
    }

    private RecyclerView mMallRecycle;
    private LinearLayout mLinearPrice, mLinearScreening;
    private TextView mSynthesise, mSaleNum, mSalePrice, mScreening;
    private ImageView mImgPrice;
    private RelativeLayout mErrorLayout;
    private View mConditionLayout;
    private View mEmptyLayout;
    private View mConditionEmptyLayout;
    private SmartRefreshLayout mSmartRefreshLayout;

    private ArrayList<CategoryGoods> mList =  new ArrayList<>();
    private ClassificationMallAdapter mAdapter;
    private int mPage = 1;
    private int mPageSize = 20;
    private String mCateId, mOriginalCateId;
    private int mTotalPage;//总页数
    private String mBind = "desc", mPrice = null, mSold = null, mShop = null, mPriceRange = null, mKeyword = null;
    private boolean mLoadMore = false;//是否从首页跳转过来的加载更多
    private boolean isLoading = false;//是否正在请求数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classification_mall);
        mCateId = getIntent().getStringExtra("cate_id");
        mOriginalCateId = getIntent().getStringExtra("original_cate_id");
        mLoadMore = getIntent().getBooleanExtra("loadMore", false);
        initView();
        setListener();
        setAdapter();
        setSmartRefreshLayout();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SEARCH_REQUEST) {
            if (resultCode == RESULT_OK) {
                mKeyword = data.getStringExtra("keyword");
            }
        }
    }

    private void initView() {
        //title
        TextView title = findViewById(R.id.title);
        title.setText(getIntent().getStringExtra("title"));

        mMallRecycle = findViewById(R.id.mall_list);
        mLinearPrice = findViewById(R.id.ll_price);
        mLinearScreening = findViewById(R.id.ll_screening);
        mSynthesise = findViewById(R.id.synthesise);
        mSaleNum = findViewById(R.id.sale_num);
        mSalePrice = findViewById(R.id.price);
        mScreening = findViewById(R.id.screening);
        mImgPrice = findViewById(R.id.price_img);
        mErrorLayout = findViewById(R.id.error);
        mSmartRefreshLayout = findViewById(R.id.refreshlayout);
        //筛选条件
        mConditionLayout = findViewById(R.id.condition_layout);

        //empty
        mEmptyLayout = findViewById(R.id.empty_layout);
        //筛选 empty
        mConditionEmptyLayout = findViewById(R.id.condition_empty_layout);

        mMallRecycle.addItemDecoration(new SpaceItemDecoration(0, Utils.dip2px(ClassificationMallActivity.this, 10), 0, Utils.dip2px(ClassificationMallActivity.this, 10)));
        mMallRecycle.setLayoutManager(new GridLayoutManager(ClassificationMallActivity.this, 2));
        mSynthesise.setSelected(true);
    }

    private void setListener() {
        mSynthesise.setOnClickListener(this);
        mLinearScreening.setOnClickListener(this);
        mLinearPrice.setOnClickListener(this);
        mSaleNum.setOnClickListener(this);
        mErrorLayout.setOnClickListener(this);
        findViewById(R.id.govisit).setOnClickListener(this);
        findViewById(R.id.search_logo).setOnClickListener(this);
        findViewById(R.id.title_left_button).setOnClickListener(this);
    }

    private void setAdapter() {
        mAdapter = new ClassificationMallAdapter(ClassificationMallActivity.this, mList);
        mMallRecycle.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                GoodsDetailActivity.jump(ClassificationMallActivity.this, mList.get(position).getItem_id());
            }
        });
    }

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
        mSmartRefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPage = 1;
                if (mLoadMore) {
                    getMoreItem();
                } else {
                    getCategoryItem();
                }
                mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                if (!mSmartRefreshLayout.isEnableLoadmore()) {
                    mSmartRefreshLayout.setEnableLoadmore(true);
                }
            }
        });

        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //未加载完，可以LoadMore
                if (mPage <= mTotalPage) {
                    mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                    if (mLoadMore) {
                        getMoreItem();
                    } else {
                        getCategoryItem();
                    }
                } else {
                    mSmartRefreshLayout.finishLoadmore();
                    mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.govisit:
                //TODO
                finish();
                break;
            case R.id.title_left_button:
                finish();
                break;
            case R.id.error:
                mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
                break;
            case R.id.synthesise://综合排序
                if (!mSynthesise.isSelected()) {
                    mBind = "desc";
                    mPrice = null;
                    mSold = null;
                    mSynthesise.setSelected(true);
                    mSaleNum.setSelected(false);
                    mSalePrice.setSelected(false);
                    mScreening.setSelected(false);
                    mImgPrice.setImageResource(R.mipmap.value_icon);
                    mSalePrice.setTextColor(getResources().getColor(R.color.color_666666));
                    mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
                }
                break;
            case R.id.sale_num://销量排序
                if (!mSaleNum.isSelected()) {
                    mSynthesise.setSelected(false);
                    mSaleNum.setSelected(true);
                    mSalePrice.setSelected(false);
                    mScreening.setSelected(false);
                    mImgPrice.setImageResource(R.mipmap.value_icon);
                    mSalePrice.setTextColor(getResources().getColor(R.color.color_666666));
                    mBind = null;
                    mPrice = null;
                    mSold = "desc";
                    mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
                }
                break;
            case R.id.ll_price://价格排序
                mBind = null;
                mPrice = null;
                mSold = null;
                if (mSalePrice.isSelected()) {
                    mPrice = "asc";
                    mSalePrice.setSelected(false);
                    mSalePrice.setTextColor(getResources().getColor(R.color.color4138));
                    mImgPrice.setImageResource(R.mipmap.value_up_icon);
                } else {
                    mPrice = "desc";
                    mImgPrice.setImageResource(R.mipmap.value_down_icon);
                    mSalePrice.setTextColor(getResources().getColor(R.color.color4138));
                    mSalePrice.setSelected(true);
                    mSynthesise.setSelected(false);
                    mSaleNum.setSelected(false);
                    mScreening.setSelected(false);
                }
                mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
                break;
            case R.id.ll_screening://筛选
                if (mScreening.isSelected()) {
                } else {
//                    mSalePrice.setSelected(false);
//                    mSynthesise.setSelected(false);
//                    mSaleNum.setSelected(false);
//                    mScreening.setSelected(true);
//                    mImgPrice.setImageResource(R.mipmap.value_icon);
//                    mSalePrice.setTextColor(getResources().getColor(R.color.color_666666));
                    showBottomDialog();
                }
                break;
            case R.id.search_logo:
                SearchActivity.jump(ClassificationMallActivity.this, SEARCH_REQUEST, true);
                break;
        }
    }

    /**
     * 展示筛选界面
     */
    private void showBottomDialog() {
        final Dialog dialog = new Dialog(ClassificationMallActivity.this, R.style.MyTransparentDialog);
        View view = ClassificationMallActivity.this.getLayoutInflater().inflate(R.layout.dialog_classificatin_mall_screening, null);
        final TextView jd_shop = view.findViewById(R.id.jd_shop);
        final TextView lishe_shop = view.findViewById(R.id.lishe_shop);
        TextView reset = view.findViewById(R.id.reset);
        TextView sure = view.findViewById(R.id.sure);
        ImageView dissmiss = view.findViewById(R.id.dissmiss);
        final EditText price_low = view.findViewById(R.id.price_low);
        final EditText price_height = view.findViewById(R.id.price_high);

        if (mShop != null) {
            if (mShop.equals("0")) {
                jd_shop.setSelected(true);
                lishe_shop.setSelected(false);
                jd_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_red);
                lishe_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_normal);
            } else if (mShop.equals("1")) {
                jd_shop.setSelected(false);
                lishe_shop.setSelected(true);
                lishe_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_red);
                jd_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_normal);
            }
        }

        if (mPriceRange != null) {
            String[] ranges = mPriceRange.split(",");
            if (ranges.length > 0) {
                price_low.setText(ranges[0]);
                if (ranges.length > 1) {
                    price_height.setText(ranges[1]);
                }
            }
        }

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    //dialog 点击事件
                    case R.id.jd_shop:
                        jd_shop.setSelected(true);
                        lishe_shop.setSelected(false);
                        mShop = "0";
                        jd_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_red);
                        lishe_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_normal);
                        break;
                    case R.id.lishe_shop:
                        jd_shop.setSelected(false);
                        lishe_shop.setSelected(true);
                        mShop = "1";
                        lishe_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_red);
                        jd_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_normal);
                        break;
                    case R.id.reset:
                        jd_shop.setSelected(false);
                        lishe_shop.setSelected(false);
                        mShop = null;
                        mPriceRange = null;
                        jd_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_normal);
                        lishe_shop.setBackgroundResource(R.drawable.bg_classification_mall_screening_text_normal);
                        price_low.setText("");
                        price_height.setText("");
                        break;
                    case R.id.sure:
                        String low = price_low.getText().toString().trim();
                        String height = price_height.getText().toString().trim();
                        if (!TextUtils.isEmpty(low)) {
                            mPriceRange = low;
                        } else {
                            mPriceRange = "0";
                        }
                        if (!TextUtils.isEmpty(height)) {
                            mPriceRange += "," + height;
                        } else {
                            mPriceRange += ",0";
                        }
                        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
                        dialog.dismiss();
                        mScreening.setSelected(false);
                        break;
                    case R.id.dissmiss:
                        dialog.dismiss();
                        mScreening.setSelected(false);
                        break;
                }
            }
        };
        jd_shop.setOnClickListener(listener);
        lishe_shop.setOnClickListener(listener);
        reset.setOnClickListener(listener);
        sure.setOnClickListener(listener);
        dissmiss.setOnClickListener(listener);

        dialog.setContentView(view);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
        dialog.show();
    }

    public void getCategoryItem() {
        if (mEmptyLayout.getVisibility() == View.VISIBLE) {
            mEmptyLayout.setVisibility(View.GONE);
        }
        if (mErrorLayout.getVisibility() == View.VISIBLE) {
            mErrorLayout.setVisibility(View.GONE);
        }
        if (!isLoading) {
            isLoading = true;
            try {
                ClassificationPresenter.getInstance().categoryItems(mCateId, mOriginalCateId, mBind, mPrice, mSold, mShop, mPriceRange, mPage, mPageSize, listener);
            } catch (Exception e) {
                e.printStackTrace();
                toast(getString(R.string.data_parse_fail));
            }
        }
    }

    public void getMoreItem() {
        if (mEmptyLayout.getVisibility() == View.VISIBLE) {
            mEmptyLayout.setVisibility(View.GONE);
        }
        if (mErrorLayout.getVisibility() == View.VISIBLE) {
            mErrorLayout.setVisibility(View.GONE);
        }
        if (!isLoading) {
            isLoading = true;
            try {
                ClassificationPresenter.getInstance().getMoreItems(mCateId, mBind, mPrice, mSold, mShop, mPriceRange, mPage, mPageSize, listener);
            } catch (Exception e) {
                e.printStackTrace();
                toast(getString(R.string.data_parse_fail));
            }
        }
    }

    private DataResponseListener<DataPageItemBody<CategoryGoods>> listener = new DataResponseListener<DataPageItemBody<CategoryGoods>>() {
        @Override
        public void onSuccess(DataPageItemBody<CategoryGoods> dataResponse) {
            isLoading = false;

            if (mPage == 1) {
                mSmartRefreshLayout.finishRefresh(0, true);
                mList.clear();
                mAdapter.notifyDataSetChanged();
            } else {
                mSmartRefreshLayout.finishLoadmore(0, true);
            }

            mPage++;
            if (dataResponse != null) {
                mTotalPage = dataResponse.getTotalPage();
                mList.addAll(dataResponse.getItems());
            }

            if (mList.size() > 0) {
                mConditionLayout.setVisibility(View.VISIBLE);
                mEmptyLayout.setVisibility(View.GONE);
                mConditionEmptyLayout.setVisibility(View.GONE);
                mAdapter.notifyDataSetChanged();
            } else {
                showEmpty();
                mSmartRefreshLayout.setEnableLoadmore(false);
            }
        }

        @Override
        public void onFail(String failMessage) {
            isLoading = false;

            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            if (mList.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                showEmpty();
            }
            toast("没有该类型的商品");
        }

        @Override
        public void onError(Throwable e) {
            isLoading = false;

            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            if (mList.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                showError();
            }

            Log.e("TAG", "e = " + e.toString());
            toast(R.string.network_or_server_exception);
        }
    };

    private void showError() {
        if (mList.size() > 0) {
            mList.clear();
            mAdapter.notifyDataSetChanged();
        }
        mErrorLayout.setVisibility(View.VISIBLE);
    }

    private void showEmpty() {
        if (mList.size() > 0) {
            mList.clear();
            mAdapter.notifyDataSetChanged();
        }
        //根据筛选是否显示判断 筛选数据为空or全部数据为空
        if (mConditionLayout.getVisibility() == View.VISIBLE) {
            mConditionEmptyLayout.setVisibility(View.VISIBLE);
        } else {
            mEmptyLayout.setVisibility(View.VISIBLE);
        }
    }

}
